package server

import (
	"common/config"
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"order/internal/models/dao"
	"order/internal/rpc"
	pb "order/proto"
	pay "pay/proto"
)

type Server struct {
	pb.UnimplementedOrderServer
}

func (Server) CreateOrder(ctx context.Context, request *pb.CreateOrderRequest) (*pb.CreateOrderResponse, error) {
	var goods dao.Good
	err := config.DB.Where("id=?", request.GoodsId).Find(&goods).Limit(1).Error
	if err != nil {
		return nil, err
	}
	if int64(goods.GoodsStock) < request.GoodsNum {
		return nil, errors.New("商品库存不够")
	}
	order := dao.Order{
		OrderSn:       uuid.NewString(),
		UserId:        int(request.UserId),
		OrderTitle:    request.OrderTitle,
		OrderPrice:    float64(request.OrderPrice),
		AmountPrice:   float64(request.OrderPrice),
		OrderMessage:  request.OrderMessage,
		CouponId:      int(request.CouponId),
		UserAddressId: int(request.UserAddressId),
		PayStatus:     request.PayType,
		GoodsNum:      int(request.GoodsNum),
	}
	err = config.DB.Create(&order).Error
	if err != nil {
		return nil, err
	}
	createPay, _ := rpc.PayClient.CreatePay(ctx, &pay.CreatePayRequest{
		Subject:    request.OrderTitle,
		OrderSn:    order.OrderSn,
		OrderPrice: fmt.Sprintf("%.2f", request.OrderPrice),
	})
	return &pb.CreateOrderResponse{Url: createPay.Url}, nil
}

func (Server) UpdateOrder(ctx context.Context, request *pb.UpdateOrderRequest) (*pb.UpdateOrderResponse, error) {
	config.DB.Where("id=?", request.OrderId).Update("order_status", request.OrderStatus)
	return &pb.UpdateOrderResponse{}, nil
}
